package com.huajx.mina.tcpserver.handler;

import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.huajx.mina.tcpserver.message.RequestMessage;

/**
 * 请求处理工厂类
 * <p>
 * 根据消息命令，获取相应的处理适配器
 *
 * @author xhye
 */
public abstract class RequestHandlerFactory extends IoHandlerAdapter {
    private static final Logger logger = LoggerFactory.getLogger(RequestHandlerFactory.class);

    /**
     * 根据命令关键字，获取具体消息处理适配器
     * <p>
     * 由子类实现
     *
     * @param request
     * @return
     */
    protected abstract HandlerAdapter getHandler(RequestMessage request);

    @Override
    public void messageReceived(IoSession session, Object message) throws Exception {
        if (message == null) {
            return;
        }

        RequestMessage request = new RequestMessage();

        request.setMessage(message);
        request.setSession(session);

        HandlerAdapter handler = getHandler(request);

        if (handler != null) {
            handler.handler(request);
        }
    }

    @Override
    public void sessionOpened(IoSession session) throws Exception {
        if (logger.isInfoEnabled()) {
            logger.info("开启连接...");
        }
    }

    @Override
    public void sessionClosed(IoSession session) throws Exception {
        if (logger.isInfoEnabled()) {
            logger.info("连接关闭");
        }
        session.closeOnFlush();
    }

    @Override
    public void sessionIdle(IoSession session, IdleStatus status) throws Exception {
        if (logger.isDebugEnabled()) {
            logger.debug("sessionIdle()... from " + session.getRemoteAddress());
        }
        session.closeOnFlush();
    }

    @Override
    public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
        if (logger.isWarnEnabled()) {
            logger.warn(
                    "EXCEPTION, please implement " + getClass().getName() + ".exceptionCaught() for proper handling:",
                    cause);
        }
    }
}
